package com.hrc.rpc.netty;

import com.hrc.rpc.config.RpcProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {
    public static final RpcProperties rpcProperties;
    public static final String serverAddress = "127.0.0.1";
    private static final ServerBootstrap bootstrap;
    private static final EventLoopGroup bossGroup;
    private static final EventLoopGroup workerGroup;

    static {
        rpcProperties = RpcProperties.getInstance();
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerChannelInitializer());
    }

    public static void main(String[] args) {
        new NettyServer().run();
    }

    public void run() {
        try {
            ChannelFuture channelFuture = bootstrap.bind(serverAddress, rpcProperties.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
